import router, { constantRoutes, systemRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import cloneDeep from 'lodash/cloneDeep'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      const dynamicMenus = store.getters.dynamicMenus
      if (hasGetUserInfo && dynamicMenus.length > 0) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          await store.dispatch('project/changeDynamicMenus') // 获取项目数据
          // 生成动态路由
          addDynamicRoutes(store.getters.dynamicMenus)
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      NProgress.done()
    }
  }
})

function addDynamicRoutes(dynamicMenus) {
  const savedRoutes = localStorage.getItem('dynamicRoutes')
  if (savedRoutes) {
    const routes = JSON.parse(savedRoutes)
    const projectIndexRoute = constantRoutes.find(route => route.name === 'ProjectIndex').children.find(item => item.name === 'projectList')

    if (projectIndexRoute) {
      projectIndexRoute.children = routes.map(route => {
        return {
          ...route,
          component: route.component || (() => import('@/views/projectManage/projectList/ListIndex.vue')) // 如果没有 component，给一个默认的组件
        }
      })
    }

    const systemSettingRoute = constantRoutes.find(route => route.name === 'SystemSetting')
    if (systemSettingRoute) {
      systemSettingRoute.children = getSystemRoutes()
    }

    setTimeout(() => {
      router.selfAddRoutes(constantRoutes) // 添加路由
    }, 50)
    return
  }

  const projectIndexRoute = constantRoutes.find(route => route.name === 'ProjectIndex').children.find(item => item.name === 'projectList')
  if (projectIndexRoute) {
    projectIndexRoute.children = dynamicMenus
  }

  router.selfAddRoutes(constantRoutes)
}

function getSystemRoutes() {
  // 处理系统设置菜单，根据登录用户的角色添加路由
  const cpRoutes = cloneDeep(systemRoutes)
  const systemSettingRoute = cpRoutes.find(route => route.name === 'SystemSetting')
  if (!systemSettingRoute || systemSettingRoute.children.length === 0) {
    return []
  }
  // 第一级子菜单
  const firstChildren = systemSettingRoute.children
  const firstRoutes = []
  firstChildren.forEach(firRoute => {
    const roles = firRoute.meta.roles || []
    if (roles && roles.length > 0 && roles.includes(store.getters.roleName)) {
      firstRoutes.push(firRoute)
    }
    // 第二级子菜单
    const secondChildren = firRoute.children
    const filterSecond = []
    if (secondChildren.length > 0) {
      secondChildren.forEach(secRoute => {
        const roles = secRoute.meta.roles || []
        if (roles && roles.length > 0 && roles.includes(store.getters.roleName)) {
          filterSecond.push(secRoute)
        }
      })
      firRoute.children = filterSecond
    }
  })
  return firstRoutes
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
